package com.wangfei.lecture.socket;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClient {

    private String hostname;
    private int port;
    Socket socketClient;

    public SocketClient(String hostname, int port){
        this.hostname = hostname;
        this.port = port;
    }

    public void connect() throws UnknownHostException, IOException{
        System.out.println("Attempting to connect to "+hostname+":"+port);
        socketClient = new Socket(hostname,port);
        System.out.println("Connection Established");
    }

    public void readResponse() throws IOException{
        String userInput;
        System.out.println(socketClient);
        try(BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream(),"UTF-8"));) {
            writer.write("Hello. Server!");
            writer.flush();
            System.out.println("Response from server:");
            while ((userInput = stdIn.readLine()) != null) {
                System.out.println(userInput);
            }
        } catch (Exception e) {
            throw e;
        }


    }
    public static void main(String arg[]){
        //Creating a SocketClient object
        SocketClient client = new SocketClient ("localhost",9990);
        try {
            //trying to establish connection to the server
            client.connect();
//            client.sendMessage();
            //if successful, read response from server
            client.readResponse();

        } catch (UnknownHostException e) {
            System.err.println("Host unknown. Cannot establish connection");
        } catch (IOException e) {
            System.err.println("Cannot establish connection. Server may not be up."+e.getMessage());
            e.printStackTrace();
        }
    }
}